<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table'
import type { scmGoodsData } from '#/views/backend/scmGoods/config'

import { h, markRaw, onMounted, ref } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'
import { useAccessStore, useUserStore } from '@vben/stores'

import { useDebounceFn } from '@vueuse/core'
import { Button, Image, ImagePreviewGroup, Input, message, Popconfirm, Space, Spin, Tag } from 'ant-design-vue'

import countTabs from '#/adapter/component/count-tabs.vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { allIndex, getGoodsStyleCategory, getTreeAll, syncErp } from '#/api/goods/scmGoods'
import { getWareHouse } from '#/api/goodsPurchase'
import { GoodsPurchseDetailindex, navList } from '#/api/goodsPurchaseDetail'
import { requestClient } from '#/api/request'
import { AdminGoodsCategory } from '#/api/spuBom'
import { completeCategoryPaths, completePaths, getNowTimeStr, getUrl } from '#/utils'
import TwoFields from '#/views/backend/modules/two-fields.vue'

import ScmGooDetail from './modules/scmGooDetail.vue'

const userStore = useUserStore()
const categoryOptions = ref([]) // 货品分类树
const timeCategoryOptions = ref([]) // 时间
const keyword = ref('')
const keyword1 = ref('')
const fetching = ref(false)
const GoodsCategory = ref<any>([])

// 获取风格
async function fetchGoodsStyleCategory({ keyword = '' }: Record<string, any>) {
  const { list } = await getGoodsStyleCategory({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    is_mini: true,
  })
  return list.map((item: any) => ({
    label: item.style_category_name,
    value: item.id,
  }))
}
// 获取仓库
async function fetgetWareHouse({ keyword = '' }: Record<string, any>) {
  const { list } = await getWareHouse({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.WarehouseName,
    value: item.id,
  }))
}

const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'goods_goods_no',
      label: '货号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'template_template_no',
      label: '简码',
      operator: 'LIKE',
    },
    {
      component: 'Cascader',
      fieldName: 'category',
      label: '货品分类',
      componentProps: {
        options: categoryOptions,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
        multiple: true,
      },
      operator: '123',
    },
    {
      component: 'Cascader',
      fieldName: 'time_category',
      label: '时间分类',
      operator: '123',
      componentProps: {
        options: timeCategoryOptions,
        placeholder: '时间分类',
        showSearch: true,
        allowClear: true,
        multiple: true,
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
        allowClear: true,
      },
      fieldName: 'created_realname',
      label: '下单人',
      operator: 'LIKE',
    },

    {
      component: 'RangePicker',
      componentProps: {
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'goodsPurchase_purchase_date',
      operator: 'RANGE',
      label: '采购日期',
    },
    {
      component: 'RangePicker',
      componentProps: {
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },

        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'created_time',
      operator: 'RANGE',
      label: '下单日期',
    },

    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchGoodsStyleCategory,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'goods_one_style_id',
      label: '一级风格',
      operator: 'IN',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '引流款',
            value: 1,
          },
          {
            label: '基本款',
            value: 2,
          },
        ],
        showSearch: true,
      },
      fieldName: 'goods_three_style_id',
      operator: 'IN',
      label: '三级风格',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '全部',
            value: '',
          },
          {
            label: '已推送',
            value: 1,
          },
          {
            label: '未推送',
            value: 0,
          },
        ],
        placeholder: '同步',
        showSearch: true,
      },
      fieldName: 'goods_erp_id',
      operator: '123',
      defaultValue: '',
      label: '同步',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '全部',
            value: '',
          },
          {
            label: '已审核推送',
            value: 1,
          },
          {
            label: '未审核',
            value: 0,
          },
        ],
        showSearch: true,
        operator: '123',
      },
      fieldName: 'goodsPurchase_posted',
      defaultValue: '',
      operator: '123',
      label: '采购单',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'goodsPurchase_goods_purchase_sn',
      label: '采购单号',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        mode: 'multiple',
        options: [
          {
            label: '成品#首单',
            value: '8',
          },
          {
            label: '加工#补单',
            value: '9',
          },
          {
            label: '加工#首单',
            value: '10',
          },
          {
            label: '成品#补单',
            value: '11',
          },
          {
            label: '成品#加单',
            value: '12',
          },
          {
            label: '加工#加单',
            value: '13',
          },
          { label: '待买手拆分', value: '99' },
        ],
        showSearch: true,
      },
      fieldName: 'goodsPurchase_purchase_type',
      operator: 'IN',
      label: '采购性质',
    },

    {
      component: markRaw(TwoFields),
      fieldName: 'plan_total_num',
      disabledOnChangeListener: false,
      label: '下单数量',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        placeholder: '范围筛选',
      },
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'supply_SupplyNa',
      label: '供货商',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'goods_sale_price',
      label: '零售价',
      operator: '=',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'goods_distribution_price',
      label: '分销价',
      operator: '=',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'goods_goods_name',
      label: '品名',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '待完善',
            value: 0,
          },
          {
            label: '已完善',
            value: 1,
          },
        ],
        showSearch: true,
      },
      label: '价格填写状态',
      fieldName: 'complete_price',
      operator: '123',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '未分仓',
            value: 0,
          },
          {
            label: '已分仓',
            value: 1,
          },
        ],
        showSearch: true,
      },
      label: '是否分仓',
      fieldName: 'w_sku_id',
      operator: '123',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'goods_buyer',
      label: '买手',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'goods_merchandiser',
      label: '跟单',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        mode: 'multiple',
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '待提交',
            value: 0,
          },
          {
            label: '审批中',
            value: 10,
          },
          {
            label: '正常通过',
            value: 20,
          },
          {
            label: '已拒绝',
            value: 30,
          },
        ],
        showSearch: true,
      },
      label: '审批状态',

      fieldName: 'goodsPurchase_approval_state',
      operator: 'IN',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          mode: 'multiple',
          api: fetgetWareHouse,
          // 禁止本地过滤
          filterOption: false,

          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword1.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword1.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'goodsPurchase_warehouse_id',
      label: '仓库',
      operator: 'IN',
      mode: 'multiple',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: GoodsCategory,
        showSearch: true,
        mode: 'multiple',
      },
      fieldName: 'data_type',
      defaultValue: userStore.userInfo.category_arr,
      operator: '123',
      label: '数据品类',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}

// 仓库多选筛选：goodsPurchase.warehouse_id    IN   [1,2,3,4]     有仓库远程下拉接口
// 审批状态多选：goodsPurchase.approval_state   IN   [0,10,20]      可先固定审批状态：0=待提交，10审批中，20=正常通过，30=已拒绝
const currentFormValues = ref()
const gridOptions: VxeTableGridOptions<scmGoodsData> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    {
      field: 'created.realname',
      fixed: 'left', // 固定在最左侧
      title: '下单人',
      width: 70,
    },
    { title: '下单时间', field: 'created_time', width: 160, fixed: 'left' },
    { field: 'goodsPurchase.purchase_date', title: '采购日期', fixed: 'left', width: 120 },
    { field: 'expected_completion_date', title: '交期', width: 120, fixed: 'left' },
    {
      field: 'goods.erp_id',

      fixed: 'left',
      title: '货品',
      width: 70,
      slots: { default: 'erp_id' },
    },
    {
      title: '采购单',
      field: 'goodsPurchase.posted',
      sortable: false,
      width: '70',
      fixed: 'left',
      slots: { default: 'posted' },
    },
    {
      title: '采购单号',
      field: 'goodsPurchase.goods_purchase_sn',
      sortable: false,
      width: 120,
      fixed: 'left',
    },
    {
      title: '货号',
      field: 'goods.goods_no',
      sortable: false,
      width: 100,
      fixed: 'left',
    },
    {
      title: '简码',
      field: 'template.template_no',
      sortable: false,
      width: 120,
      fixed: 'left',
    },
    {
      title: '采购性质',
      field: 'purchase_type',
      sortable: false,
      width: 100,
      slots: { default: 'purchase_type' },
    },
    { title: '下单数量', field: 'plan_total_num', width: 80 },
    { title: '颜色', field: 'color.name', width: 70 },
    { title: '款式分类', field: 'cate_name', width: 180 },
    {
      field: 'goods.goods_images',
      title: '货品图片',
      width: 50,
      slots: { default: 'imgs' },
    },

    { title: '收货仓库', field: 'warehouse.WarehouseName', width: 150 },
    { title: '供货商', field: 'supply.SupplyNa', width: 150 },
    { title: '采购价', field: 'price', width: 70 },
    { title: '零售价', field: 'goods.sale_price', width: 70 },
    { title: '分销价', field: 'goods.distribution_price', width: 70 },
    { title: '吊牌价', field: 'goods.tag_price', width: 100 },
    { title: '尺码组', field: 'sizeGroup.name', width: 100 },
    { title: '品名', field: 'goods.goods_name', width: 100 },
    {
      title: '价格填写状态',
      field: 'complete_price',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已完善',
            value: 1,
          },
          { color: 'error', label: '待完善', value: 0 },
        ],
      },
    },
    { title: '价格要求完成时间', field: 'complete_price_at', width: 140 },
    {
      title: '是否分仓',
      field: 'w_sku_id',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已分仓',
            value: 1,
          },
          { color: 'error', label: '未分仓', value: 0 },
        ],
      },
    },
    { title: '买手', field: 'goods.buyer', width: 100 },
    { title: '跟单', field: 'goods.merchandiser', width: 100 },
    { title: '风格分类', field: 'style_cate_name', width: 150 },
    { title: '时间分类', field: 'time_cate_name', width: 150 },
    { title: '面料', field: 'attr_fabric', width: 100 },
    { title: '里料', field: 'attr_lining', width: 100 },
    { title: '加工面料', field: 'attr_process_fabric', width: 100 },
    { title: '加工里料', field: 'attr_process_lining', width: 100 },
    { title: '最后修改时间', field: 'updated_time', width: 160 },
    { title: '作废人', field: 'deleteInfo.realname', width: 160 },
    { title: '作废时间', field: 'deleted_at', width: 160 },
    { title: '作废原因', field: 'deleted_reason', width: 160 },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 180,
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        // 1. 过滤空值
        const search: any[] = []
        for (const [key, value] of Object.entries(formValues)) {
          if (value === null || value === '' || value === undefined) continue
          const fieldSchema = formOptions.schema.find((i: any) => i.fieldName === key)
          let field = key
          // 单独处理特殊映射（只转换明确需要转换的字段）
          const specialMappings: Record<string, string> = {
            // 下单人字段：将created_realname转换为created.realname
            created_realname: 'created.realname',
            goodsPurchase_purchase_date: 'goodsPurchase.purchase_date',
            goods_one_style_id: 'goods.one_style_id',
            goods_three_style_id: 'goods.three_style_id',
            goods_erp_id: 'goods.erp_id',
            goodsPurchase_posted: 'goodsPurchase.posted',
            goodsPurchase_goods_purchase_sn: 'goodsPurchase.goods_purchase_sn',
            goods_goods_no: 'goods.goods_no',
            template_template_no: 'template.template_no',
            goodsPurchase_purchase_type: 'goodsPurchase.purchase_type',
            goods_sale_price: 'goods.sale_price',
            goods_distribution_price: 'goods.distribution_price',
            goods_goods_name: 'goods.goods_name',
            goods_buyer: 'goods.buyer',
            goods_merchandiser: 'goods.merchandiser',
            goodsPurchase_approval_state: 'goodsPurchase.approval_state',
            goodsPurchase_warehouse_id: 'goodsPurchase.warehouse_id',
            supply_SupplyNa: 'supply.SupplyNa',
          }

          // 只转换特殊映射中明确指定的字段
          if (specialMappings[key]) {
            field = specialMappings[key]
          }
          // 处理特殊字段格式
          let fieldValue = value
          // 处理created_at时间范围格式
          if (key === 'goodsPurchase_purchase_date' && Array.isArray(value) && value.length === 2) {
            // 将日期范围数组转换为字符串格式："开始时间,结束时间"
            fieldValue = value.join(',')
          }
          if (key === 'created_time' && Array.isArray(value) && value.length === 2) {
            // 将日期范围数组转换为字符串格式："开始时间,结束时间"
            fieldValue = value.join(',')
          }

          if (key === 'time_category') {
            fieldValue = completePaths(value, timeCategoryOptions.value)
          }
          if (key === 'category') {
            fieldValue = completeCategoryPaths(value, categoryOptions.value)
          }
          if (key === 'plan_total_num') {
            fieldValue = value.join(',')
          }
          search.push({
            field,
            val: fieldValue,
            operator: fieldSchema?.operator,
            render: fieldSchema?.render,
          })
        }
        currentFormValues.value = search
        // 2. 调接口
        const res = await GoodsPurchseDetailindex({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: 'goods_id,desc',
          quick_search: quick_search.value,
          navValue: activeKey.value,
        })
        const res1 = await navList({
          search,
          order: 'id,desc',
        })
        tabsList.value = res1
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  id: 'goods_purchase_detail',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
}

onMounted(async () => {
  const cateRes = await allIndex()
  categoryOptions.value = cateRes.list
  const timeRes = await getTreeAll()
  timeCategoryOptions.value = timeRes
  const parmas = {
    is_select: true,
    page: 1,
    initKey: 'id',
    select: true,
  }
  AdminGoodsCategory(parmas).then((res: any) => {
    GoodsCategory.value = res.list.map((item) => ({
      label: item.name,
      value: item.id,
    }))
  })
})

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions })

// 在数据刷新后重新检查选中状态
function onRefresh() {
  gridApi.query()
}

/**
 *  推送erp
 */
async function pushErp(row: any) {
  const hideLoading = message.loading({
    content: `正在推送${row.goods.goods_name}`,
    duration: 3,
  })
  syncErp({ goods_id: row.goods.goods_id })
    .then((res) => {
      if (res.data.code === 0) {
        message.error(res.data.msg)
      } else if (res.data.code === 1) {
        message.success({
          content: `推送成功${row.goods.goods_name}`,
        })
      }
      hideLoading()
      onRefresh()
    })
    .catch(() => {
      hideLoading()
    })
}

/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}

const getDownload = () => {
  const dom = document.createElement('a')
  const url = `${getUrl()}/static/template/商企下单导入模版.xlsx`
  dom.setAttribute('href', url)
  dom.setAttribute('download', '商企下单导入模版.xlsx')
  dom.click()
}
// tab
const activeKey = ref('approval_state20')
const tabsList: any = ref([{ title: '正常' }, { title: '未推送' }, { title: '已推送' }, { title: '已作废' }])
// 切换tab
function resetQuery() {
  gridApi.query()
}

/**
 * 导出数据函数
 */
const ExportData = () => {
  // 准备默认请求参数
  const defaultParams = {
    order: 'goods_id,desc',
    quick_search: quick_search.value,
    export: true,
    search: currentFormValues.value,
    navValue: activeKey.value,
  }

  // 合并默认参数和自定义参数
  const params: any = { ...defaultParams }
  requestClient
    .get('/admin/ScmGoods/GoodsPurchseDetailindex', params, {
      responseReturn: 'body',
      responseType: 'blob',
      headers: {
        Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      },
    })
    .then((response) => {
      // 由于设置了responseReturn: 'body'，这里应该直接是Blob对象
      let blob = response as Blob
      // 简单的类型检查
      if (blob instanceof Blob) {
      } else {
        blob = new Blob([JSON.stringify(response)], { type: 'application/json' })
      }
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      // 使用传入的fileName或生成带时间戳的默认文件名
      const timestr = getNowTimeStr()
      a.download = `大货采购明细_${timestr}.xlsx`
      // 将a标签添加到DOM以确保兼容性
      document.body.append(a)
      a.click()
      // 下载完成后清理
      setTimeout(() => {
        a.remove()
        window.URL.revokeObjectURL(url)
        message.success('下载成功')
      }, 100)
    })
}

// 导入文件列表
const fileList = ref<any[]>([])
// 上传组件引用
const uploadRef = ref()
// 处理导入成功回调，检查业务逻辑是否成功
const handleImportSuccess = (response: any, file: any, fileList: any[]) => {
  // 如果业务逻辑失败(code=0)，手动触发错误处理
  if (response.code === 0) {
    handleImportError(response, file, fileList)
  } else {
    message.success('导入成功')
    // 导入成功后刷新数据
    gridApi.query()
  }
}

// 处理导入失败回调
const handleImportError = (error: any, file: any, fileList: any[]) => {
  console.log('Import error details:', error)
  // 尝试从不同位置获取错误信息
  const errorMsg = error.msg || error.response?.data?.msg || error.message || '未知错误'
  message.error(`导入失败: ${errorMsg}`)
}
const accessStore = useAccessStore()
const customHeaders = {
  batoken: accessStore.accessToken ?? '',
  'X-Requested-With': 'XMLHttpRequest',
}

const [DetailModal, DetailModalApi] = useVbenModal({
  connectedComponent: ScmGooDetail,
})

// 单独编辑
function openModal(res: any, but: string) {
  DetailModalApi.setData({
    ids: res.goods.goods_id,
    purchase_detail_id: res.id,
    view: but,
  }).open()
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space style="width: 450px">
            <!--            <Upload-->
            <!--              ref="uploadRef"-->
            <!--              :headers="customHeaders"-->
            <!--              :action="`${getUrl()}/admin/ScmGoods/GoodsPurchseDetailimportData`"-->
            <!--              :on-error="handleImportError"-->
            <!--              :on-success="handleImportSuccess"-->
            <!--              :file-list="fileList"-->
            <!--              :multiple="false"-->
            <!--              accept=".xlsx,.xls"-->
            <!--              :show-upload-list="false"-->
            <!--            >-->
            <!--              <template #default>-->
            <!--                <Button type="primary">-->
            <!--                  <AntUploadOutlined />-->
            <!--                  导入数据-->
            <!--                </Button>-->
            <!--              </template>-->
            <!--            </Upload>-->
            <!--            <Button type="primary" @click="getDownload">下载模板</Button>-->
            <Button type="primary" @click="ExportData">导出</Button>
            <!--            <Button type="primary" @click="openBatch">批量下单</Button>-->
          </Space>
          <div style="margin-top: 10px; width: 1000px">
            <count-tabs v-model:active-key="activeKey" :list="tabsList" @click-tab="resetQuery()" :disabled="false" />
          </div>
        </div>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通过简码、货号、品名模糊搜索" style="width: 200px; margin-right: 8px" @change="doSearch" />
      </template>
      <template #imgs="{ row }">
        <ImagePreviewGroup>
          <template v-for="item in row.goods?.goods_images">
            <Image :src="item" />
          </template>
        </ImagePreviewGroup>
      </template>
      <!-- 操作列插槽 -->
      <template #erp_id="{ row }">
        <Tag v-if="row.goods?.erp_id > 0" color="green">已推送</Tag>
        <Tag v-else color="red">未推送</Tag>
      </template>
      <template #posted="{ row }">
        <Tag v-if="row.goodsPurchase?.posted > 0" color="green">已审核</Tag>
        <Tag v-else color="red">未审核</Tag>
      </template>

      <template #purchase_type="{ row }">
        <Tag v-if="row.goodsPurchase?.purchase_type === 8" color="green">成品#首单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 9" color="red">加工#补单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 10" color="blue">加工#首单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 11" color="blue">成品#补单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 12" color="blue">成品#加单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 13" color="blue">加工#加单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 99" color="blue">待买手拆分</Tag>
      </template>

      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <template v-if="!row.goods?.erp_id">
            <Popconfirm title="货号为空，自动生成新的。确定要推送到ERP系统吗？" ok-text="确认" cancel-text="取消" @confirm="pushErp(row)">
              <Button type="primary" title="添加数据到ERP系统的货品档案" class="my-green-btn" size="small">同步ERP</Button>
            </Popconfirm>
          </template>
          <Button type="primary" size="small" @click="openModal(row, 'edit')">编辑</Button>
        </Space>
      </template>
    </Grid>
    <DetailModal />
    <batchOrderingModal />
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
